import React, { useState, useEffect } from 'react'
import BScroll from '@better-scroll/core'
import PullDown from '@better-scroll/pull-down'

import './better-scroll.scss'

const TIME_BOUNCE = 800
const THRESHOLD = 70
const STOP = 100
const loadingSrc = 'https://img.lanrentuku.com/img/allimg/1609/5-160914192R3.gif'

BScroll.use(PullDown)

const BetterScrolls = (props) => {

  const { children, pull } = props
  let refreshTime = null
  let timer = null
  let bs = null
  const [beforePullDown, setBeforePullDown] = useState(true) // 
  const [isPullingDown, setIsPullingDown] = useState(false) // 是否在下拉中

  useEffect(() => {
    // 页面加载完毕初始化bs
    window.onload = init() 
  }, [])

   const init = () => {
    if(!bs) {
      setTimeout(() => {
        let bs = new BScroll('.better-scroll-box', {
          scrollY: true,
          startY: 0,
          bounceTime: TIME_BOUNCE,
          useTransition: false,
          pullDownRefresh: {
            threshold: THRESHOLD,
            stop: STOP
          },
          click: true,
          scrollX: true,
          eventPassthrough: 'horizontal',
        // and so on
        })
        bs.on('pullingDown', () => pullingDown(bs))
      }, 500)
    }
  }

  // 加入节流
  const pullingDown = async (bs) => {
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
    if (!isPullingDown) {
      setBeforePullDown(false)
      setIsPullingDown(true)
      pull().then(() => {
        timer = setTimeout(() => {
          setIsPullingDown(false)
          finishPullDown(bs)
        }, 800)
      })
      return
    }
  }

  // 完成刷新
  const finishPullDown = (bs) => {
    bs.finishPullDown()
    refreshTime = setTimeout(() => {
      setBeforePullDown(true)
      bs.refresh()
      clearTimeout(refreshTime)
    }, 1500)
  }

  return (
    <div className='better-scroll-box'>
      <div>
        <div className="pulldown-scroller">
          <div className="pulldown-wrapper">
            <div style={{ display: `${ beforePullDown ? 'block' : 'none' }` }} className=''>
              <span>手给我松开</span>
            </div>
            <div style={{ display: `${ !beforePullDown ? 'block' : 'none' }` }} className='loading'>
              <div style={{ display: `${ isPullingDown ? 'block' : 'none' }` }}>
                <img className='loading-img' src={'https://img.lanrentuku.com/img/allimg/1212/5-121204194026-50.gif'} />
              </div>
              <div style={{ display: `${ !isPullingDown ? 'block' : 'none' }` }} className=''>
                <span>刷新完成</span>
              </div>
            </div>
          </div>
        </div>
      { children }
      </div>
    </div>
  )
}

export default BetterScrolls